package org.spindle.soasuite.datasource.helper;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hsqldb.Server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class HSQLDBHibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static Server hsqlServer;


    private static SessionFactory buildSessionFactory() {
        try {
            Class.forName("org.hsqldb.jdbcDriver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try {


            try {
                hsqlServer = new Server();

                // HSQLDB prints out a lot of informations when
                // starting and closing, which we don't need now.
                // Normally you should point the setLogWriter
                // to some Writer object that could store the logs.
                hsqlServer.setLogWriter(null);
                hsqlServer.setSilent(true);


                // The actual database will be named 'xdb' and its
                // settings and data will be stored in files
                // testdb.properties and testdb.script
                hsqlServer.setDatabaseName(0, "xdb");
                hsqlServer.setDatabasePath(0, "file:testdb");


                // Start the database!
                hsqlServer.start();

            } catch (Exception e) {
                e.printStackTrace();
            }
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Server getHsqlServer() {
        return hsqlServer;
    }

    public static void shutdownConnection() throws SQLException {
        Connection con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/xdb", "sa",
                "");
        String sql = "SHUTDOWN";
        java.sql.Statement stmt = con.createStatement();
        stmt.executeUpdate(sql);
        stmt.close();
    }
}